package routing.producer;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-09-19
 * @time: 09:14:55
 */
public class Main {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 配置工厂参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        // 2. 获取连接
        Connection connection = factory.newConnection();
        // 3. 获取通道
        Channel channel = connection.createChannel();
        // 4. 声明交换机
        channel.exchangeDeclare(Constants.DIRECT_EXCHANGE, BuiltinExchangeType.DIRECT,true,false,false,null);
        // 5. 声明队列
        channel.queueDeclare(Constants.DIRECT_QUEUE1,true,false,false,null);
        channel.queueDeclare(Constants.DIRECT_QUEUE2,true,false,false,null);
        // 6. 绑定交换机与队列, 指明绑定关系
        // DIRECT_QUEUE1, 绑定 orange
        channel.queueBind(Constants.DIRECT_QUEUE1,Constants.DIRECT_EXCHANGE,"orange");
        // DIRECT_QUEUE2, 绑定 green, black
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"green");
        channel.queueBind(Constants.DIRECT_QUEUE2,Constants.DIRECT_EXCHANGE,"black");

        // 7. 发送消息
        String msg_orange = "hello touting, I am an orange";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"orange",null,msg_orange.getBytes());
        String msg_green = "hello touting, I am an green";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"green",null,msg_green.getBytes());
        String msg_black = "hello touting, I am an black";
        channel.basicPublish(Constants.DIRECT_EXCHANGE,"black",null,msg_black.getBytes());
        // 8. 释放资源
        channel.close();
        connection.close();
    }
}
